// backtestUtils.js - 存放回测相关的工具函数

/**
 * 计算回测结果
 * @param {Object} backtestResults - 回测结果
 * @param {Object} backtestSummary - 回测摘要
 */
export const calculateBacktestResults = (backtestResults, backtestSummary) => {
  if (!backtestResults || !backtestResults.equityCurve || !backtestResults.equityCurve.length) return
  
  const equityCurve = backtestResults.equityCurve
  const trades = backtestResults.trades
  
  // 计算总收益率
  const initialEquity = equityCurve[0].equity
  const finalEquity = equityCurve[equityCurve.length - 1].equity
  backtestSummary.totalReturn = ((finalEquity - initialEquity) / initialEquity) * 100
  
  // 计算年化收益率
  const days = equityCurve.length
  const years = days / 365
  backtestSummary.annualReturn = years > 0 ? (Math.pow(1 + backtestSummary.totalReturn / 100, 1 / years) - 1) * 100 : 0
  
  // 计算夏普比率
  const returns = []
  for (let i = 1; i < equityCurve.length; i++) {
    const ret = (equityCurve[i].equity - equityCurve[i - 1].equity) / equityCurve[i - 1].equity
    returns.push(ret)
  }
  
  const avgReturn = returns.length > 0 ? returns.reduce((a, b) => a + b, 0) / returns.length : 0
  const stdDev = returns.length > 1 ? Math.sqrt(returns.map(x => Math.pow(x - avgReturn, 2)).reduce((a, b) => a + b, 0) / returns.length) : 0
  backtestSummary.sharpeRatio = stdDev === 0 ? 0 : avgReturn / stdDev
  
  // 计算最大回撤
  let peak = initialEquity
  let maxDrawdown = 0
  
  for (const item of equityCurve) {
    if (item.equity > peak) peak = item.equity
    const drawdown = (peak - item.equity) / peak
    if (drawdown > maxDrawdown) maxDrawdown = drawdown
  }
  
  backtestSummary.maxDrawdown = maxDrawdown * 100
  
  // 计算胜率
  const profitableTrades = trades.filter(t => t.profit && t.profit > 0).length
  backtestSummary.totalTrades = trades.filter(t => t.profit !== undefined).length
  backtestSummary.winRate = backtestSummary.totalTrades > 0 ? (profitableTrades / backtestSummary.totalTrades) * 100 : 0
}

/**
 * 绘制回测结果图表
 * @param {Object} backtestChart - 图表容器
 * @param {Object} results - 回测结果
 */
export const drawBacktestChart = (backtestChart, results) => {
  if (!backtestChart || !results || !results.equityCurve || !results.equityCurve.length) {
    console.warn('图表容器或数据不存在')
    return
  }
  
  import('echarts').then(echarts => {
    // 销毁旧图表实例
    if (backtestChart.chartInstance) {
      backtestChart.chartInstance.dispose()
      backtestChart.chartInstance = null
    }
    
    // 初始化图表
    backtestChart.chartInstance = echarts.init(backtestChart)
    
    // 准备图表数据
    const dates = results.equityCurve.map(item => item.date)
    const equityValues = results.equityCurve.map(item => item.equity)
    
    const option = {
      title: {
        text: '回测结果 - 权益曲线',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const date = params[0].axisValue
          const value = params[0].data.toFixed(2)
          return `${date}<br/>权益: $${value}`
        }
      },
      xAxis: {
        type: 'category',
        data: dates,
        scale: true,
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        axisLabel: {
          formatter: function(value) {
            return value.split(' ')[0] // 只显示日期部分
          }
        }
      },
      yAxis: {
        type: 'value',
        scale: true,
        splitLine: { show: true },
        axisLabel: {
          formatter: '${value}'
        }
      },
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        containLabel: true
      },
      series: [
        {
          name: '权益',
          type: 'line',
          data: equityValues,
          smooth: true,
          showSymbol: false,
          lineStyle: {
            width: 2,
            color: '#5470c6'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(84, 112, 198, 0.5)'
              },
              {
                offset: 1,
                color: 'rgba(84, 112, 198, 0.1)'
              }
            ])
          }
        }
      ]
    }
    
    backtestChart.chartInstance.setOption(option)
    
    // 响应窗口大小变化
    const resizeHandler = () => {
      if (backtestChart.chartInstance) {
        backtestChart.chartInstance.resize()
      }
    }
    window.addEventListener('resize', resizeHandler)
  })
}